package com.xl6667.job;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xl6667.domain.entity.Article;
import com.xl6667.service.ArticleService;
import com.xl6667.util.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * redis定时更新到数据库
 */
@Component
@Slf4j
public class RedisScheduled {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private RedisCache redisCache;
    @Scheduled(cron = "0 0/55 * * * ?")
    public void articleViewCount(){
        log.info("定时更新从redis更新浏览量数据库");
        Map<String, Integer> cacheMap = redisCache.getCacheMap("article:viewCount");
        List<Article> articleList = cacheMap.entrySet().stream()
                .map(entry -> new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue()))
                .collect(Collectors.toList());
        for (Article article : articleList) {
            LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Article::getId,article.getId());
            updateWrapper.set(Article::getViewCount,article.getViewCount());
            articleService.update(null,updateWrapper);
        }
    }
}
